package com.example.juc.big_talk_concurrent.chapter6.article3;

import java.util.HashMap;
import java.util.Map;

public class Test {
    private static String str1;
    // final修饰说明str2这个引用不能变为指向其他变量，比如让str2再重新指向另一个new出来的ThreadLocal
    private static final ThreadLocal<String> str2 = new ThreadLocal<>();

    private static final ThreadLocal<Map<String, Integer>> map = new ThreadLocal<>();

    public static void main(String[] args) throws InterruptedException {
        str1 = "main";
        str2.set("main");

        map.set(new HashMap<>());
        map.get().put("张三", 18);

        Thread thread = new Thread("child") {
            @Override
            public void run() {
                super.run();
                str1 = "child";
                str2.set("child");

                // 在子线程中需要重新set，不然会报空指针，ThreadLocal线程隔离后子线程拿不到主线程中set进去的map
                map.set(new HashMap<>());
                map.get().put("李四", 20);

                for (String key : map.get().keySet()) {
                    System.out.println(key + ", " + map.get().get(key));
                }
            }
        };

        thread.start();
        thread.join();

        System.out.println("str1 = " + str1);
        System.out.println("str2 = " + str2.get());

        for (String key : map.get().keySet()) {
            System.out.println(key + ", " + map.get().get(key));
        }
    }
}
